package com.yeskery.nut.application;

import com.yeskery.nut.core.NutException;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 应用阻塞器
 * @author sprout
 * @version 1.0
 */
public class ApplicationBlocker {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(ApplicationBlocker.class.getName());

    /** 阻塞队列 */
    private final BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(1);

    /** 是否已阻塞 */
    private final AtomicBoolean blocked = new AtomicBoolean(false);

    /**
     * 执行阻塞
     */
    public void block() {
        if (blocked.compareAndSet(false, true)) {
            try {
                blockingQueue.take();
            } catch (InterruptedException e) {
                throw new NutException("Blocking Exception", e);
            }
        } else {
            logger.log(Level.WARNING, "Multiple Invoke Method[block()]");
        }
    }

    /**
     * 释放阻塞
     */
    public void release() {
        if (blocked.compareAndSet(true, false)) {
            if(!blockingQueue.offer(0)) {
                logger.log(Level.WARNING, "Multiple Invoke Method[release()]");
            }
        } else {
            logger.log(Level.WARNING, "Multiple Invoke Method[release()]");
        }
    }
}
